// pages/character/create/create.js
var db = require('../../../utils/dataBind.js')
var formList = require('formListInit.js')
const app = getApp()

Page(Object.assign({

  /**
   * 页面的初始数据
   */
  data: {
    gender: {
      data: ['男', '女'],
      index: 0
    },
    // 种族初始值
    raceInitData: {
      index: 0,
      data: [],
      nameList: []
    },
    // 职业初始值
    classesInitData: {
      index: 0,
      data: [],
      nameList: []
    },
    // 阵营绑定值
    alignmentCache: {
      index: 0,
      data: [],
      nameList: []
    },
    // 人物基本信息列表配置
    characterListInit: formList.characterListInit,
    // 人物基本能力列表配置
    abilityListInit: formList.abilityListInit,
    // 人物技能列表配置
    skillsListInit: formList.skillsListInit,
    // 负重能力列表配置
    loadListInit: formList.loadListInit,
    showTopTips:false,
    // 基本信息提交变量
    character:{
      nameZh: '李有志',
      gender: '男'
      // nameEn: '',
      // playerName: app.globalData.openid
    },
    // 属性信息提交变量
    ability:{
      savingThrows:{
        fortitude: ''
      }
    },
    // 属性信息输入值(力量，敏捷，智力，体质，感知，魅力)
    abilityInput: {
      strength: 0,
      dexterity: 0,
      intelligence: 0,
      constitution: 0,
      wisdom: 0,
      charisma: 0
    },
    // 属性信息调整值(力量，敏捷，智力，体质，感知，魅力)
    abilityModifier: {
      strength: 0,
      dexterity: 0,
      intelligence: 0,
      constitution: 0,
      wisdom: 0,
      charisma: 0
    },
    // 技能信息提交变量
    skills:[
      {
        skillName: '',
        skillLevel: '',
        skillMod: '',
        keyAbility: ''
      }
    ],
    // 负重信息提交变量
    load:{},
    // 当前选择种族暂存变量
    raceCache: {},
    // 当前选择职业暂存变量
    classCache: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    wx.cloud.init()
    wx.setNavigationBarTitle({
      title: '新建角色',
    })
    Promise.all([new Promise(function (resolve, reject) { that.getRaceInit(resolve, reject) }), new Promise(function (resolve, reject) { that.getClassesInit(resolve, reject) })]).then(function () {
      that.setRaceValue(that.data.raceCache)
      that.setClassValue(that.data.classCache)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 性别选项改变事件
   */
  bindGenderChange: function (e) {
    this.data.gender.index = parseInt(e.detail.value)
    this.setData({
      gender: this.data.gender
    })
    this.data.character.gender = e.detail.value === '0' ? '男' : '女'
    // 判断种族是否选择
    if (Object.keys(this.data.raceCache).length > 0) {
      this.setRaceValue(this.data.raceCache)
    }
  },

  /**
   * 阵营选项改变事件
   */
  bindAlignmentChange: function (e) {
    this.data.alignmentCache.index = parseInt(e.detail.value)
    this.setData({
      alignmentCache: this.data.alignmentCache
    })
    this.data.character.alignment = this.data.alignmentCache.data[parseInt(e.detail.value)]
  },

  /**
   * 种族选项改变事件
   */
  bindRaceChange: function (e) {
    this.data.raceInitData.index = parseInt(e.detail.value)
    this.setData({
      raceInitData: this.data.raceInitData
    })
    this.data.raceCache = this.data.raceInitData.data[parseInt(e.detail.value)]
    this.setRaceValue(this.data.raceCache)
  },
  // 设定种族相关值
  setRaceValue: function (currentRace) {
    // console.log(currentRace)
    // 种族影响得相关值设定
    this.data.character.raceName = currentRace.raceNameCh
    this.data.character.languages = currentRace.languages.join('，')
    this.data.character.size = currentRace.size
    // 年龄设置（种族基础年龄+职业年龄调整值）
    this.data.character.age = this.realAge(this.data.raceCache.age.minAge, this.data.classCache.minAge[this.data.raceCache.raceNameEn])
    this.data.ability.speed = currentRace.speed
    this.data.abilityModifier = currentRace.raceModify
    // 获取身高体重调整值（掷色）
    let raceHeightModifier = this.shakeDice(currentRace.height.modifier[0], currentRace.height.modifier[1])
    let raceWeightModifier = this.shakeDice(currentRace.weight.modifier[0], currentRace.weight.modifier[1])
    if (this.data.character.gender === '女') {
      // 英尺英寸模式身高变量（备用）（女）
      // let realHeightFt = Math.floor(currentRace.height.base[0][0] + (raceHeightModifier.sum + currentRace.height.base[0][1]) / 12)
      // let realHeightIn = (raceHeightModifier.sum + currentRace.height.base[0][1]) % 12
      // 英寸模式身高设定（女）
      let realHeightIn = currentRace.height.base[0][0] * 12 + currentRace.height.base[0][1] + raceHeightModifier.sum
      // 英尺英寸模式身高设定（备用）
      // this.data.character.height = realHeightFt + '尺' + realHeightIn + '英寸'
      this.data.character.height = realHeightIn
      this.data.character.weight = currentRace.weight.base[0] + raceHeightModifier.sum * raceWeightModifier.sum
    } else {
      // 英尺英寸模式身高变量（备用）（男）
      // let realHeightFt = Math.floor(currentRace.height.base[1][0] + (raceHeightModifier.sum + currentRace.height.base[1][1]) / 12)
      // let realHeightIn = (raceHeightModifier.sum + currentRace.height.base[1][1]) % 12
      // 英寸模式身高设定（男）
      let realHeightIn = currentRace.height.base[1][0] * 12 + currentRace.height.base[1][1] + raceHeightModifier.sum
      // 英尺英寸模式身高设定（备用）
      // this.data.character.height = realHeightFt + '尺' + realHeightIn + '英寸'
      this.data.character.height = realHeightIn
      this.data.character.weight = currentRace.weight.base[1] + raceHeightModifier.sum * raceWeightModifier.sum
    }
    this.setData({
      character: this.data.character,
      abilityModifier: this.data.abilityModifier
    })
    // console.log(this.data.character)
  },

  /**
   * 职业选项改变事件
   */
  bindClassChange: function (e) {
    this.data.classesInitData.index = e.detail.value
    this.setData({
      classesInitData: this.data.classesInitData
    })
    this.data.classCache = this.data.classesInitData.data[parseInt(e.detail.value)]
    this.setClassValue(this.data.classCache)
  },
  // 设定职业相关值
  setClassValue: function (currentClass) {
    // console.log(currentClass)
    // 职业影响得相关值设定
    this.data.character.classesName = currentClass.classNameCh
    this.data.alignmentCache.data = currentClass.alignment
    this.data.character.alignment = currentClass.alignment[0]
    this.data.character.possessions = "金币: " + this.shakeDice(currentClass.money[0], currentClass.money[1]).sum * currentClass.money[2]
    this.data.ability.hp = currentClass.hp
    // 遍历获取职业自带技能
    for (let item of currentClass.classSkill){
      item.skillLevel = 1
      item.skillMod = currentClass.skillMod
    }
    this.data.skills = currentClass.classSkill
    // 年龄设置（种族基础年龄+职业年龄调整值）
    this.data.character.age = this.realAge(this.data.raceCache.age.minAge, this.data.classCache.minAge[this.data.raceCache.raceNameEn])
    this.setData({
      character: this.data.character,
      ability: this.data.ability,
      skills: this.data.skills,
      alignmentCache: this.data.alignmentCache
    })
  },

  /**
   * 年龄计算（种族基础年龄+职业年龄调整值）
   */
  realAge: function (baseAge, ageModifier) {
    return parseInt(baseAge) + this.shakeDice(ageModifier[0], ageModifier[1]).sum
  },

  /**
   * 添加技能
   */
  addSkillItem: function () {
    var newSkillItem = {
      index: this.data.skillsListInit.length,
      skillName: {
        type: 'text',
        dataName: 'skills.skillName'
      },
      skillLevel: {
        type: 'number',
        dataName: 'skills.skillLevel'
      },
      skillMod: {
        type: 'number',
        dataName: 'skills.skillMod'
      }
    }
    this.data.skills.push({
      skillName: '',
      skillLevel: '',
      skillMod: ''
    })
    this.data.skillsListInit.push(newSkillItem);
    this.setData({
      skillsListInit: this.data.skillsListInit
    });
    // console.log(this.data.skillsListInit);
  },

  /**
   * 删除技能
   */
  deleteSkillItem: function (e) {
    var selectedItemIndex = e.currentTarget.dataset.index
    // console.log(e.currentTarget);
    // var itemIndex = this.data.skillsListInit.findIndex(function(item){
    //   return item.index === selectedItemIndex
    // });
    this.data.skills.splice(selectedItemIndex, 1)
    this.data.skillsListInit.splice(selectedItemIndex, 1)
    this.setData({
      skillsListInit: this.data.skillsListInit
    })
    console.log(this.data.skills);
  },

  /**
   * 提交表单
   */
  submit: function () {
    if (this.data.character.nameZh === '') {
      var that = this;
      this.setData({
        showTopTips: true
      });
      setTimeout(function () {
        that.setData({
          showTopTips: false
        });
      }, 3000);
    } else {
      for (let key in this.data.abilityInput){
        // console.log(this.data.abilityInput[key], this.data.abilityModifier[key])
        this.data.ability[key] = this.data.abilityInput[key] + this.data.abilityModifier[key]
      }
      var requestParams = {
        character: this.data.character,
        ability: this.data.ability,
        skills: this.data.skills,
        load: this.data.load
      }
      console.log(requestParams)
      wx.request({
        url: app.globalData.domain +'/assistant/character/create',
        header: {
          'content-type': "application/json;charset=utf-8"
        },
        data: requestParams,
        method:"POST",
        success: res => {
          console.log(res.data)
        }
      })
    }
  },

  /**
   * 获取种族初始值
   */
  getRaceInit(resolve, reject) {
    const db = wx.cloud.database()
    const that = this
    db.collection('race')
      // .where({
      //   publishInfo: {
      //     country: 'United States'
      //   }
      // })
      .get({
        success(res) {
          that.data.raceInitData.data = res.data
          res.data.map(item => {
            that.data.raceInitData.nameList.push(item.raceNameCh + ' ' + item.raceNameEn)
          })
          that.setData({
            raceInitData: that.data.raceInitData
          })
          that.data.raceCache = res.data[0]
          resolve()
        }
      })
  },
  /**
   * 获取职业初始值
   */
  getClassesInit(resolve, reject) {
    const db = wx.cloud.database()
    const that = this
    db.collection('classes')
      // .where({
      //   publishInfo: {
      //     country: 'United States'
      //   }
      // })
      .get({
        success(res) {
          that.data.classesInitData.data = res.data
          res.data.map(item => {
            that.data.classesInitData.nameList.push(item.classNameCh + ' ' + item.classNameEn)
          })
          that.setData({
            classesInitData: that.data.classesInitData
          })
          that.data.classCache = res.data[0]
          resolve()
        }
      })
  }

}, db))

//http://localhost:8089
//https://dndgay.ga